package co.edu.unal.satacredito.administration.view.user;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import co.edu.unal.satacredito.administration.service.user.UserViewService;
import co.edu.unal.satacredito.administration.view.general.AdministrationBean;
import co.edu.unal.satacredito.infrastructure.dto.UserDTO;
import co.edu.unal.satacredito.mediation.UserEJBLocal;

@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean extends AdministrationBean {

	private String username;
	private String password;
	private boolean isLoggedIn;

	private UserViewService userService;

	@EJB
	private UserEJBLocal userEJB;

	@PostConstruct
	public void init() {
		userService = new UserViewService();
		System.out.println("Ejecutando postconstruct");
	}

	public String doLogin() {

		System.out.println("Ejecutando dologin");

		UserDTO userDTO = userEJB.getUserFromLoginService(username, password);

		System.out.println("Finalizando llamada a EJB");

		if (userDTO == null) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Error validando usuario. Compruebe datos"));
			return FAILED;
		}

		isLoggedIn = true;
		userService.saveUserInSession(userDTO);
		return SUCCESS;
	}

	public void checkLoggedIn(ComponentSystemEvent event) {
		if (!isLoggedIn) {
			doRedirect("/public/login.jsf");
		}
	}

	public String doLogout() {
		userService.doLogout();
		isLoggedIn = false;
		doRedirect("/public/login.xhtml");
		return LOGOUT;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public boolean isLoggedIn() {
		return isLoggedIn;
	}

	public void setLoggedIn(boolean isLoggedIn) {
		this.isLoggedIn = isLoggedIn;
	}

}
